package com.numberone.iotplatform.controller;

import com.numberone.iotplatform.entity.DeviceEvent;
import com.numberone.iotplatform.service.DeviceEventService;
import org.springframework.web.bind.annotation.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 设备事件记录的RESTful API控制器
 * 所有接口路径都在 /api/devices/{deviceId}/events 之下
 */
@RestController
@RequestMapping("/devices/{deviceId}/events")
public class DeviceEventController {

    @Autowired
    private DeviceEventService deviceEventService;

    /**
     * 获取指定设备的分页事件记录列表，支持按条件筛选。
     *
     * @param deviceId    设备ID，从URL路径中获取
     * @param eventType   事件类型 (可选的请求参数)
     * @param startTime   查询起始时间 (可选的请求参数, ISO 8601格式, e.g., 2023-08-09T10:00:00)
     * @param endTime     查询结束时间 (可选的请求参数)
     * @param pageable    Spring Data JPA 提供的分页和排序参数 (e.g., ?page=0&size=10&sort=eventTime,desc)
     * @return 分页后的事件列表
     */
    @GetMapping
    public ResponseEntity<Page<DeviceEvent>> getEventsByDeviceId(
            @PathVariable Long deviceId,
            @RequestParam(required = false) String eventType,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime,
            Pageable pageable
    ) {
        Page<DeviceEvent> events = deviceEventService.findEventsByDeviceId(deviceId, eventType, startTime, endTime, pageable);
        return ResponseEntity.ok(events);
    }
}